<template>
  <div class="chat-container">
    <!-- 侧边栏 -->
    <div class="sidebar" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
      <div class="sidebar-header">
        <a-avatar :size="40" :src="currentUser.avatar || 'https://joeschmoe.io/api/v1/random'"></a-avatar>
        <span v-if="!sidebarCollapsed" class="user-name">{{ currentUser.nickname }}</span>
        <a-button type="text" class="collapse-btn" @click="toggleSidebar">
          <menu-fold-outlined v-if="!sidebarCollapsed" />
          <menu-unfold-outlined v-else />
        </a-button>
      </div>

      <!-- 会话列表 -->
      <a-tabs v-if="!sidebarCollapsed" v-model:activeKey="activeTabKey" @change="onTabChange">
        <a-tab-pane key="1" tab="消息">
          <div class="conversation-list">
            <div v-for="(conversation, index) in conversations" :key="conversation.id || index"
              class="conversation-item" :class="{ active: currentConversation?.id === conversation.id }"
              @click="selectConversation(conversation)">
              <a-badge :count="conversation.unreadCount">
                <a-avatar :size="40" :src="conversation.avatar"></a-avatar>
              </a-badge>
              <div class="conversation-info">
                <div class="conversation-name">{{ conversation.name }}</div>
                <div class="conversation-last-message">{{ getMessageText(conversation.lastMessage) }}</div>
              </div>
              <div class="conversation-time">{{ formatTime(conversation.lastMessageTime || conversation.lastTime) }}
              </div>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" tab="联系人">
          <div class="contact-list">
            <!-- 搜索框 -->
            <div class="contact-search">
              <a-input v-model:value="contactSearchKeyword" placeholder="搜索联系人..." :prefix="h('search-outlined')"
                @input="filterContacts" allowClear />
            </div>

            <!-- 联系人列表 -->
            <div class="contact-items">
              <div v-if="filteredContacts.length === 0" class="empty-contacts">
                <user-outlined />
                <p>暂无联系人</p>
              </div>
              <div v-for="(contact, index) in filteredContacts" :key="contact.id" class="contact-item"
                @click="startChat(contact)">
                <a-badge :dot="contact.status === 'ONLINE'" :color="getStatusColor(contact.status)">
                  <a-avatar :size="40" :src="contact.avatar || getDefaultAvatar(contact.nickname)">
                    {{ contact.nickname?.charAt(0) }}
                  </a-avatar>
                </a-badge>
                <div class="contact-info">
                  <div class="contact-name">{{ contact.nickname }}</div>
                  <div class="contact-status">{{ getStatusText(contact.status) }}</div>
                </div>
                <div class="contact-actions">
                  <a-tooltip title="发送消息">
                    <a-button type="text" size="small" @click.stop="startChat(contact)">
                      <message-outlined />
                    </a-button>
                  </a-tooltip>
                </div>
              </div>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>

      <!-- 折叠侧边栏时的图标导航 -->
      <div v-else class="icon-nav">
        <a-tooltip placement="right" title="消息">
          <a-button type="text" shape="circle">
            <message-outlined />
          </a-button>
        </a-tooltip>
        <a-tooltip placement="right" title="联系人">
          <a-button type="text" shape="circle">
            <team-outlined />
          </a-button>
        </a-tooltip>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-content">
      <template v-if="currentConversation">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="chat-title">
            {{ currentConversation.name }}
            <a-tag v-if="currentConversation.type === 'GROUP'" color="blue">群聊</a-tag>
          </div>
          <div class="chat-actions">
            <a-tooltip title="语音通话">
              <a-button type="text" shape="circle" @click="startVoiceCall">
                <phone-outlined />
              </a-button>
            </a-tooltip>
            <a-tooltip title="视频通话">
              <a-button type="text" shape="circle" @click="startVideoCall">
                <video-camera-outlined />
              </a-button>
            </a-tooltip>
            <a-tooltip title="退出登录">
              <a-button type="text" shape="circle" @click="handleLogout">
                <poweroff-outlined />
              </a-button>
            </a-tooltip>
            <a-tooltip title="更多">
              <a-dropdown>
                <a-button type="text" shape="circle">
                  <ellipsis-outlined />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="1">查看资料</a-menu-item>
                    <a-menu-item key="2">清空聊天记录</a-menu-item>
                    <a-menu-item key="3" danger>删除会话</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-tooltip>
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="message-list" ref="messageList">
          <!-- 加载更多按钮 -->
          <div v-if="messages.length > 0" class="load-more-container">
            <a-button type="text" size="small" @click="loadMoreMessages" class="load-more-btn">
              <up-outlined />
              加载更多消息
            </a-button>
          </div>

          <!-- 消息项 -->
          <!-- 修改后的消息列表部分 -->
          <div v-for="(message, index) in messages" :key="message.id || index" class="message-wrapper">
            <!-- 时间分隔线 -->
            <div v-if="shouldShowTimeBreak(message, index)" class="time-break">
              <span class="time-break-text">{{ formatDateBreak(message.timestamp) }}</span>
            </div>

            <!-- 用户分隔线 -->
            <div v-if="shouldShowUserBreak(message, index)" class="user-break">
              <div class="user-break-line"></div>
            </div>

            <!-- 合并后的消息行结构 -->
            <div class="message-row"
              :class="{ 'message-row-self': Number(message.senderId) === Number(currentUser.id) }">
              <!-- 对方消息 -->
              <template v-if="Number(message.senderId) !== Number(currentUser.id)">
                <div class="message-avatar">
                  <a-avatar v-if="shouldShowAvatar(message, index)" :size="36" :src="getSenderAvatar(message.senderId)">
                    {{ getSenderName(message.senderId)?.charAt(0) }}
                  </a-avatar>
                  <div v-else class="avatar-space"></div>
                </div>

                <div class="message-content">
                  <div v-if="currentConversation.type === 'GROUP' && isFirstMessageInGroup(message, index)"
                    class="message-sender">
                    {{ getSenderName(message.senderId) }}
                  </div>

                  <div class="message-bubble other-bubble">
                    {{ getMessageText(message.content) }}
                  </div>

                  <div v-if="isLastMessageInGroup(message, index)" class="message-time">
                    {{ formatTime(message.timestamp) }}
                  </div>
                </div>

                <div class="message-spacer"></div>
              </template>

              <!-- 自己消息 -->
              <template v-else>
                <div class="message-spacer"></div>

                <div class="message-content">
                  <div class="message-bubble self-bubble">
                    {{ getMessageText(message.content) }}
                    <div v-if="isLastMessageInGroup(message, index)" class="message-status">
                      <check-outlined v-if="message.status === 'SENT'" />
                      <check-circle-outlined v-else-if="message.status === 'DELIVERED'" />
                      <check-circle-filled v-else-if="message.status === 'read'" />
                      <loading-outlined v-else />
                    </div>
                  </div>

                  <div v-if="isLastMessageInGroup(message, index)" class="message-time">
                    {{ formatTime(message.timestamp) }}
                  </div>
                </div>

                <div class="message-avatar">
                  <a-avatar v-if="shouldShowAvatar(message, index)" :size="36"
                    :src="currentUser.avatar || 'https://joeschmoe.io/api/v1/random'">
                    {{ currentUser.nickname?.charAt(0) }}
                  </a-avatar>
                  <div v-else class="avatar-space"></div>
                </div>
              </template>
            </div>
          </div>

          <!-- 空消息状态 -->
          <div v-if="messages.length === 0" class="empty-messages">
            <message-outlined />
            <p>还没有消息，开始聊天吧！</p>
          </div>
        </div>

        <!-- 消息输入区域 -->
        <div class="message-input">
          <div class="input-toolbar">
            <a-tooltip title="表情">
              <a-button type="text" shape="circle">
                <smile-outlined />
              </a-button>
            </a-tooltip>
            <a-tooltip title="图片">
              <a-button type="text" shape="circle">
                <picture-outlined />
              </a-button>
            </a-tooltip>
            <a-tooltip title="文件">
              <a-button type="text" shape="circle">
                <paper-clip-outlined />
              </a-button>
            </a-tooltip>
            <a-tooltip title="语音消息">
              <a-button type="text" shape="circle">
                <audio-outlined />
              </a-button>
            </a-tooltip>
          </div>
          <a-textarea v-model:value="messageInput" placeholder="输入消息..." :auto-size="{ minRows: 2, maxRows: 5 }"
            @keydown.enter.prevent="sendMessage" />
          <div class="input-actions">
            <a-button type="primary" @click="sendMessage">发送</a-button>
          </div>
        </div>
      </template>

      <!-- 未选择会话时的提示 -->
      <div v-else class="empty-chat">
        <inbox-outlined />
        <p>选择一个联系人或群组开始聊天</p>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, nextTick, computed, watch, h } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user';
import { useChatStore } from '../stores/chat';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  MessageOutlined,
  TeamOutlined,
  PhoneOutlined,
  VideoCameraOutlined,
  EllipsisOutlined,
  PoweroffOutlined,
  SmileOutlined,
  PictureOutlined,
  PaperClipOutlined,
  AudioOutlined,
  SoundOutlined,
  PlayCircleOutlined,
  FileOutlined,
  InboxOutlined,
  SearchOutlined,
  UserOutlined,
  UpOutlined,
  EyeOutlined,
  CheckOutlined,
  CheckCircleOutlined,
  CheckCircleFilled,
  LoadingOutlined,
  ClockCircleOutlined,
  DownloadOutlined,
  FileTextOutlined,
  FilePdfOutlined,
  FileImageOutlined
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

export default defineComponent({
  components: {
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    MessageOutlined,
    TeamOutlined,
    PhoneOutlined,
    VideoCameraOutlined,
    EllipsisOutlined,
    PoweroffOutlined,
    SmileOutlined,
    PictureOutlined,
    PaperClipOutlined,
    AudioOutlined,
    SoundOutlined,
    PlayCircleOutlined,
    FileOutlined,
    InboxOutlined,
    SearchOutlined,
    UserOutlined,
    UpOutlined,
    CheckOutlined,
    EyeOutlined,
    FileTextOutlined,
    FileImageOutlined,
    FilePdfOutlined,
    DownloadOutlined
  },
  setup() {
    const userStore = useUserStore();
    const chatStore = useChatStore();
    const router = useRouter();

    // 侧边栏折叠状态
    const sidebarCollapsed = ref(false);

    // 当前用户信息
    const currentUser = computed(() => ({
      id: userStore.userId,
      username: userStore.username,
      nickname: userStore.nickname,
      avatar: userStore.avatar
    }));

    // 会话列表
    const conversations = computed(() => chatStore.sortedConversations);

    // 联系人列表 - 动态从API获取
    const contacts = ref([]);
    // 选项卡激活键（持久化）
    const activeTabKey = ref(localStorage.getItem('chat_active_tab') || '1');
    // 是否已恢复上次会话
    const restoredConversation = ref(false);

    // 联系人搜索
    const contactSearchKeyword = ref('');
    const filteredContacts = ref([]);

    // 加载联系人列表
    const loadContacts = async () => {
      try {
        const { getContacts } = await import('../api/chat.js');
        const contactList = await getContacts();
        contacts.value = contactList || [];
        filteredContacts.value = contacts.value;
        console.log('加载联系人列表:', contacts.value.length, '个联系人');
      } catch (error) {
        console.error('加载联系人列表失败:', error);
        contacts.value = [];
        filteredContacts.value = [];
      }
    };

    // 过滤联系人
    const filterContacts = () => {
      if (!contactSearchKeyword.value.trim()) {
        filteredContacts.value = contacts.value;
      } else {
        const keyword = contactSearchKeyword.value.toLowerCase();
        filteredContacts.value = contacts.value.filter(contact =>
          contact.nickname?.toLowerCase().includes(keyword) ||
          contact.username?.toLowerCase().includes(keyword)
        );
      }
    };

    // 获取状态颜色
    const getStatusColor = (status) => {
      switch (status) {
        case 'ONLINE': return '#52c41a';
        case 'BUSY': return '#faad14';
        case 'OFFLINE': return '#d9d9d9';
        default: return '#d9d9d9';
      }
    };

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'ONLINE': return '在线';
        case 'BUSY': return '忙碌';
        case 'OFFLINE': return '离线';
        default: return '未知';
      }
    };

    // 获取默认头像
    const getDefaultAvatar = (nickname) => {
      const colors = ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae', '#87d068'];
      const index = nickname ? nickname.charCodeAt(0) % colors.length : 0;
      return `https://ui-avatars.com/api/?name=${encodeURIComponent(nickname || 'U')}&background=${colors[index].slice(1)}&color=fff`;
    };

    // 当前选中的会话
    const currentConversation = computed(() => chatStore.currentConversation);

    // 消息列表
    const messages = computed(() => chatStore.messages);

    // 消息输入
    const messageInput = ref('');

    // 消息列表DOM引用
    const messageList = ref(null);

    // 切换侧边栏折叠状态
    const toggleSidebar = () => {
      sidebarCollapsed.value = !sidebarCollapsed.value;
    };

    // 退出登录
    const handleLogout = () => {
      try {
        chatStore.disconnect();
        chatStore.conversations = [];
        chatStore.currentConversation = null;
        chatStore.messages = [];
      } catch (e) { }
      userStore.logout();
      router.push('/');
    };

    // 选择会话
    const selectConversation = (conversation) => {
      chatStore.setCurrentConversation(conversation);

      // 滚动到底部
      scrollToBottom();
      try { localStorage.setItem('chat_last_conversation_id', conversation.id); } catch (e) { }
    };

    // 处理标签页切换
    const onTabChange = (key) => {
      activeTabKey.value = key;
      try { localStorage.setItem('chat_active_tab', key); } catch (e) { }
      if (key === '2') {
        loadContacts();
      }
    };

    // 开始与联系人聊天
    const startChat = async (contact) => {
      console.log('点击联系人，开始聊天:', contact);

      // 重新加载联系人列表
      console.log('重新加载联系人列表');
      await loadContacts();

      // 检查是否已有与该联系人的会话
      const existingConversation = conversations.value.find(
        conv => conv.type === 'PRIVATE' && conv.targetId === contact.id
      );

      if (existingConversation) {
        selectConversation(existingConversation);
      } else {
        // 创建新会话 - 增加群聊判断逻辑
        const isGroup = contact.isGroup || contact.type === 'GROUP'; // 假设联系人数据包含群组标识
        const newConversation = {
          id: isGroup ? `group_${contact.id}` : `private_${contact.id}`,
          type: isGroup ? 'GROUP' : 'PRIVATE', // 明确设置会话类型
          targetId: contact.id,
          name: contact.nickname,
          avatar: contact.avatar,
          lastMessage: '',
          lastTime: Date.now(),
          unreadCount: 0
        };

        // 添加到会话列表并选择
        chatStore.conversations.push(newConversation);
        chatStore.setCurrentConversation(newConversation);
      }
    };

    // 加载更多消息
    const loadMoreMessages = () => {
      chatStore.loadMessages(true);
    };

    // 发送消息
    const sendMessage = () => {
      if (!messageInput.value.trim() || !currentConversation.value) return;

      const messageContent = messageInput.value.trim();

      // 创建本地消息对象，立即显示在界面上
      const localMessage = {
        id: Date.now(), // 临时ID
        senderId: currentUser.value.id,
        conversationId: currentConversation.value.id,
        content: messageContent,
        contentType: 'TEXT',
        timestamp: Date.now(),
        status: 'sending' // 发送中状态
      };

      // 立即添加到本地消息列表
      chatStore.messages.push(localMessage);

      // 更新当前会话的最后消息信息
      if (currentConversation.value) {
        currentConversation.value.lastMessage = messageContent;
        currentConversation.value.lastMessageTime = Date.now();

        // 如果会话不在会话列表中，添加到列表
        const existingConv = chatStore.conversations.find(c => c.id === currentConversation.value.id);
        if (!existingConv) {
          chatStore.conversations.push({ ...currentConversation.value });
        } else {
          // 更新现有会话的信息
          existingConv.lastMessage = messageContent;
          existingConv.lastMessageTime = Date.now();
        }
      }

      // 发送到服务器
      const messageData = {
        receiverId: currentConversation.value.targetId,
        // 添加 chatType 参数
        conversationType: currentConversation.value.type, // 'PRIVATE' 或 'GROUP'
        content: messageContent,
        contentType: 'TEXT'
      };

      chatStore.sendMessage(messageData);

      // 清空输入框
      messageInput.value = '';

      // 滚动到底部
      scrollToBottom();
    };

    // 滚动消息列表到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (messageList.value) {
          messageList.value.scrollTop = messageList.value.scrollHeight;
        }
      });
    };

    // 格式化时间
    const formatTime = (timestamp) => {
      const now = dayjs();
      const time = dayjs(timestamp);

      if (now.diff(time, 'day') === 0) {
        return time.format('HH:mm');
      } else if (now.diff(time, 'day') === 1) {
        return '昨天 ' + time.format('HH:mm');
      } else if (now.diff(time, 'week') === 0) {
        return time.format('ddd HH:mm');
      } else {
        return time.format('MM-DD HH:mm');
      }
    };

    // 格式化文件大小
    const formatFileSize = (size) => {
      if (size < 1024) {
        return size + ' B';
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(1) + ' KB';
      } else if (size < 1024 * 1024 * 1024) {
        return (size / (1024 * 1024)).toFixed(1) + ' MB';
      } else {
        return (size / (1024 * 1024 * 1024)).toFixed(1) + ' GB';
      }
    };

    // 获取消息文本内容
    const getMessageText = (content) => {
      if (typeof content === 'string') {
        try {
          const parsed = JSON.parse(content);
          return parsed.text || content;
        } catch (e) {
          return content;
        }
      } else if (content && typeof content === 'object') {
        return content.text || JSON.stringify(content);
      }
      return content || '';
    };

    // 获取发送者头像
    const getSenderAvatar = (senderId) => {
      if (Number(senderId) === Number(currentUser.value.id)) {
        return currentUser.value.avatar || 'https://joeschmoe.io/api/v1/random';
      }

      const contact = contacts.value.find(c => Number(c.id) === Number(senderId));
      return contact ? contact.avatar : 'https://joeschmoe.io/api/v1/random';
    };

    // 获取发送者名称
    const getSenderName = (senderId) => {
      if (Number(senderId) === Number(currentUser.value.id)) {
        return currentUser.value.nickname;
      }

      const contact = contacts.value.find(c => Number(c.id) === Number(senderId));
      return contact ? contact.nickname : '未知用户';
    };

    // 预览图片
    const previewImage = (url) => {
      // 实现图片预览
      console.log('预览图片:', url);
    };

    // 播放语音
    const playVoice = (message) => {
      // 实现语音播放
      console.log('播放语音:', message);
    };

    // 播放视频
    const playVideo = (message) => {
      // 实现视频播放
      console.log('播放视频:', message);
    };

    // 下载文件
    const downloadFile = (message) => {
      // 实现文件下载
      console.log('下载文件:', message);
    };

    // 发起语音通话
    const startVoiceCall = () => {
      message.info('发起语音通话功能即将上线');
    };

    // 发起视频通话
    // 发起视频通话
    const startVideoCall = () => {
      message.info('发起视频通话功能即将上线');
    };

    // 判断是否显示时间分隔线
    const shouldShowTimeBreak = (message, index) => {
      if (index === 0) return true;
      const prevMessage = messages.value[index - 1];
      const currentTime = dayjs(message.timestamp);
      const prevTime = dayjs(prevMessage.timestamp);
      return currentTime.diff(prevTime, 'hour') >= 1;
    };

    // 判断是否显示用户分隔线
    const shouldShowUserBreak = (message, index) => {
      if (index === 0) return false;
      const prevMessage = messages.value[index - 1];
      return Number(message.senderId) !== Number(prevMessage.senderId);
    };

    // 判断是否为消息组中的第一条消息
    const isFirstMessageInGroup = (message, index) => {
      if (index === 0) return true;
      const prevMessage = messages.value[index - 1];
      return Number(message.senderId) !== Number(prevMessage.senderId);
    };

    // 判断是否为消息组中的最后一条消息
    const isLastMessageInGroup = (message, index) => {
      if (index === messages.value.length - 1) return true;
      const nextMessage = messages.value[index + 1];
      return Number(message.senderId) !== Number(nextMessage.senderId);
    };

    // 判断是否为消息组中的中间消息
    const isMiddleMessageInGroup = (message, index) => {
      return !isFirstMessageInGroup(message, index) && !isLastMessageInGroup(message, index);
    };

    // 判断是否应该显示头像
    const shouldShowAvatar = (message, index) => {
      return isLastMessageInGroup(message, index);
    };

    // 格式化日期分隔线
    const formatDateBreak = (timestamp) => {
      const now = dayjs();
      const time = dayjs(timestamp);

      if (now.diff(time, 'day') === 0) {
        return '今天 ' + time.format('HH:mm');
      } else if (now.diff(time, 'day') === 1) {
        return '昨天 ' + time.format('HH:mm');
      } else if (now.diff(time, 'week') === 0) {
        return time.format('dddd HH:mm');
      } else {
        return time.format('MM月DD日 HH:mm');
      }
    };

    // 格式化视频时长
    const formatDuration = (seconds) => {
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins}:${secs.toString().padStart(2, '0')}`;
    };

    // 判断文件类型
    const isTextFile = (fileName) => {
      const textExts = ['.txt', '.doc', '.docx', '.md'];
      return textExts.some(ext => fileName.toLowerCase().endsWith(ext));
    };

    const isImageFile = (fileName) => {
      const imageExts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
      return imageExts.some(ext => fileName.toLowerCase().endsWith(ext));
    };

    const isPdfFile = (fileName) => {
      return fileName.toLowerCase().endsWith('.pdf');
    };

    // 监听消息变化，自动滚动到底部
    watch(() => chatStore.messages.length, () => {
      scrollToBottom();
    });

    onMounted(() => {
      // 获取token并初始化WebSocket连接
      const token = localStorage.getItem('token');
      if (token) {
        chatStore.connectWebSocket(token);

        // 等待连接建立后加载会话列表和联系人列表
        setTimeout(() => {
          chatStore.loadConversations();
          loadContacts(); // 初始加载联系人列表
        }, 1000);
      }
    });

    // 会话列表变化时尝试恢复上次选中的会话
    watch(conversations, (list) => {
      if (restoredConversation.value) return;
      const lastId = localStorage.getItem('chat_last_conversation_id');
      if (lastId && Array.isArray(list) && list.length) {
        const conv = list.find(c => String(c.id) === String(lastId));
        if (conv) {
          selectConversation(conv);
          restoredConversation.value = true;
        }
      }
    });

    return {
      currentUser,
      sidebarCollapsed,
      conversations,
      contacts,
      currentConversation,
      messages,
      messageInput,
      messageList,
      toggleSidebar,
      handleLogout,
      selectConversation,
      startChat,
      sendMessage,
      contactSearchKeyword,
      filteredContacts,
      loadContacts,
      activeTabKey,
      onTabChange,
      filterContacts,
      getStatusColor,
      getStatusText,
      getDefaultAvatar,
      formatTime,
      formatFileSize,
      getMessageText,
      getSenderAvatar,
      getSenderName,
      previewImage,
      playVoice,
      playVideo,
      downloadFile,
      startVoiceCall,
      startVoiceCall,
      startVideoCall,
      shouldShowTimeBreak,
      shouldShowUserBreak,
      isFirstMessageInGroup,
      isLastMessageInGroup,
      isMiddleMessageInGroup,
      shouldShowAvatar,
      formatDateBreak,
      formatDuration,
      isTextFile,
      isImageFile,
      isPdfFile,
      h
    };
  }
});
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 300px;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  transition: width 0.3s;
}

.sidebar-collapsed {
  width: 60px;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
}

.user-name {
  margin-left: 12px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.collapse-btn {
  margin-left: 8px;
}

.conversation-list,
.contact-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
  display: flex;
  flex-direction: column;
}

.conversation-item,
.contact-item {
  padding: 12px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-bottom: 4px;
  transition: all 0.2s ease;
  position: relative;
}

.conversation-item:hover,
.contact-item:hover {
  background-color: #f5f5f5;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.conversation-item.active {
  background-color: #e6f7ff;
  border: 1px solid #1890ff;
}

.conversation-info {
  margin-left: 12px;
  flex: 1;
  overflow: hidden;
}

.conversation-name {
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-last-message {
  font-size: 12px;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-time {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
}

/* 联系人搜索框样式 */
.contact-search {
  padding: 8px 12px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 8px;
}

.contact-items {
  flex: 1;
  overflow-y: auto;
}

/* 联系人项目样式 */
.contact-info {
  margin-left: 12px;
  flex: 1;
  overflow: hidden;
}

.contact-name {
  font-weight: 500;
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 2px;
}

.contact-status {
  font-size: 12px;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.contact-actions {
  opacity: 0;
  transition: opacity 0.2s ease;
}

.contact-item:hover .contact-actions {
  opacity: 1;
}

/* 空状态样式 */
.empty-contacts {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #999;
  text-align: center;
}

.empty-contacts .anticon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #d9d9d9;
}

.empty-contacts p {
  margin: 0;
  font-size: 14px;
}

/* 在线状态指示器 */

/* 使用深度选择器，穿透 scoped 作用域到 AntD 内部元素 */
:deep(.ant-badge) {
  position: relative;
}

:deep(.ant-badge .ant-badge-dot) {
  width: 10px;
  height: 10px;
  border: 2px solid #fff;
  box-shadow: 0 0 0 1px #fff;
}

/* 头像样式优化 */
:deep(.ant-avatar) {
  border: 2px solid #f0f0f0;
  transition: border-color 0.2s ease;
}

.contact-item:hover :deep(.ant-avatar) {
  border-color: #1890ff;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .contact-search {
    padding: 6px 8px;
  }

  .contact-item {
    padding: 10px 8px;
  }

  .contact-name {
    font-size: 13px;
  }

  .contact-status {
    font-size: 11px;
  }
}

.icon-nav {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 0;
}

.icon-nav .ant-btn {
  margin-bottom: 16px;
}

/* 聊天区域样式 */
.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-title {
  font-size: 16px;
  font-weight: 500;
}

.chat-actions {
  display: flex;
  align-items: center;
}

.chat-actions .ant-btn {
  margin-left: 8px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

/* 消息行布局 */
.message-row {
  display: flex;
  align-items: flex-end;
  margin-bottom: 8px;
  padding: 0 16px;
}

/* 自己的消息行 - 右对齐 */
.message-row-self {
  justify-content: flex-end;
}

/* 对方的消息行 - 左对齐 */
.message-row:not(.message-row-self) {
  justify-content: flex-start;
}

/* 头像区域 */
.message-avatar {
  width: 36px;
  display: flex;
  justify-content: center;
}

.avatar-space {
  width: 36px;
  height: 36px;
}

/* 消息内容区域 */
.message-content {
  max-width: 60%;
  margin: 0 12px;
}

/* 对方消息内容左对齐 */
.message-row:not(.message-row-self) .message-content {
  text-align: left;
}

/* 自己消息内容右对齐 */
.message-row-self .message-content {
  text-align: right;
}

/* 消息气泡 */
.message-bubble {
  display: inline-block;
  padding: 10px 16px;
  border-radius: 18px;
  word-break: break-word;
  position: relative;
  max-width: 100%;
}

/* 对方的消息气泡 - 灰色 */
.other-bubble {
  background: #f5f5f5;
  color: #333;
  border-bottom-left-radius: 4px;
}

/* 自己的消息气泡 - 蓝色 */
.self-bubble {
  background: linear-gradient(135deg, #1890ff, #40a9ff);
  color: white;
  border-bottom-right-radius: 4px;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

/* 消息时间 */
.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* 自己消息的时间右对齐 */
.message-row-self .message-time {
  color: #bbb;
}

/* 消息状态 */
.message-status {
  position: absolute;
  bottom: 4px;
  right: 8px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

/* 发送者名称 */
.message-sender {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

/* 空白占位区域 */
.message-spacer {
  flex: 1;
  max-width: 25%;
}

/* 用户分隔线样式 */
.user-break {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}

.user-break-line {
  width: 60px;
  height: 1px;
  background: linear-gradient(90deg, transparent, #e8e8e8, transparent);
}

/* 时间分隔线样式 */
.time-break {
  display: flex;
  justify-content: center;
  margin: 24px 0 16px 0;
  position: relative;
}

.time-break::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, #e8e8e8 20%, #e8e8e8 80%, transparent);
  z-index: 1;
}

.time-break-text {
  background: #fff;
  padding: 4px 12px;
  font-size: 12px;
  color: #999;
  border-radius: 12px;
  border: 1px solid #e8e8e8;
  position: relative;
  z-index: 2;
}

.image-message {
  padding: 4px;
}

.image-message img {
  max-width: 100%;
  max-height: 200px;
  border-radius: 8px;
  cursor: pointer;
}

.voice-message {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.voice-message span {
  margin-left: 8px;
}

.video-message {
  padding: 4px;
  cursor: pointer;
}

.video-thumbnail {
  position: relative;
  width: 200px;
  height: 150px;
  border-radius: 8px;
  overflow: hidden;
}

.video-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 48px;
  color: rgba(255, 255, 255, 0.8);
}

.file-message {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.file-info {
  margin-left: 8px;
}

.file-name {
  font-weight: 500;
}

.file-size {
  font-size: 12px;
  color: #999;
}

.message-input {
  border-top: 1px solid #e8e8e8;
  padding: 16px;
}

.input-toolbar {
  margin-bottom: 8px;
}

.input-toolbar .ant-btn {
  margin-right: 8px;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

.empty-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
}

.empty-chat .anticon {
  font-size: 64px;
  margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: absolute;
    height: 100%;
    z-index: 10;
    background-color: white;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
  }

  .sidebar-collapsed {
    transform: translateX(-100%);
  }
}
</style>